//
//  WHYEmoticonViewModel.swift
//  emoticonKeyboard
//
//  Created by 王洪运 on 15/11/29.
//  Copyright © 2015年 王洪运. All rights reserved.
//

import UIKit

class WHYEmoticonManager {

    static let sharedManager = WHYEmoticonManager()
    
    lazy var packages = [WHYEmoticonPackage]()
    
//    MARK: - 构造函数
    private init() {
        
        packages.append(WHYEmoticonPackage(dict: ["group_name_cn": "最近"]))
        
        guard let path = NSBundle.mainBundle().pathForResource("emoticons", ofType: "plist", inDirectory: "Emoticons.bundle") else {
            QL4("文件不存在")
            return
        }
        
        guard let dict = NSDictionary(contentsOfFile: path) else {
            QL4("数据加载错误")
            return
        }
        
        let array = (dict["packages"] as! NSArray).valueForKey("id") as! [String]
        
        for id in array {
            loadInfoPlist(id)
        }
    }
    
///    最近使用的表情
    func addFavorite(emoticon: WHYEmoticon) -> () {
        
        emoticon.times++
        
        if !packages.first!.emoticons.contains(emoticon) {
            packages.first!.emoticons.insert(emoticon, atIndex: 0)
            packages.first!.emoticons.removeAtIndex(packages.first!.emoticons.count - 2)
        }
        
//        数组排序
//        packages.first!.emoticons.sortInPlace { (firstEmoticon, secondEmoticon) -> Bool in
//            firstEmoticon.times > secondEmoticon.times
//        }
//        简写数组排序
        packages.first!.emoticons.sortInPlace { $0.times > $1.times }
        
//        QL2(packages.first!.emoticons)
    }
    
    private func loadInfoPlist (id: String) {
        let path = NSBundle.mainBundle().pathForResource("info", ofType: "plist", inDirectory: "Emoticons.bundle/\(id)")!
        
        let dict = NSDictionary(contentsOfFile: path) as! [String: AnyObject]
        
        packages.append(WHYEmoticonPackage(dict: dict))
    }
    
}

//    MARK: - 显示字符串中的表情
extension WHYEmoticonManager {
    
    /// 使用正则表达式将字符串替换成带表情图片的属性字符串
    ///
    /// - parameter str:  要替换的字符串
    /// - parameter font: 字符串字体
    ///
    /// - returns: 带表情图片的属性字符串
    func emoticonText(str: String, font: UIFont) -> NSAttributedString {
        
        let strM = NSMutableAttributedString(string: str)
        
        let pattern = "\\[.*?\\]"
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        
        let results = regex.matchesInString(str,
            options: [],
            range: NSRange(location: 0, length: str.characters.count))
        
        var count = results.count
        
        while count > 0 {
            
            let result = results[--count]
            
            let range = result.rangeAtIndex(0)
            
            let emStr = (str as NSString).substringWithRange(range)
            
            if let em = checkEmoticon(emStr) {
                
                let imageText = WHYEmoticonAttachment(emoticon: em).imageText(font)
                
                strM.replaceCharactersInRange(range, withAttributedString: imageText)
            }
            
        }
        
        return strM.copy() as! NSAttributedString
    }
    
    /// 使用字符串查找表情符号
    ///
    /// - parameter str: 表情字符串
    ///
    /// - returns: 表情
    private func checkEmoticon(str: String) -> WHYEmoticon? {
        
        for p in WHYEmoticonManager.sharedManager.packages {
            
            //            简写模式
            if let em = p.emoticons.filter({ $0.chs == str }).last {
                return em
            }
            
            //            完全写法
            //            if let em1 = p.emoticons.filter({ (em) -> Bool in
            //                return em.chs == str
            //            }).last {
            //                return em1
            //            }
            
        }
        
        return nil
    }

    
}
